
// api
import menuHttp from "@/https/menu.js";
 // storage工具类，简单的封装
import pinia from '@/store/index.js';
import { userStore } from '@/store/modules/user.js';
import Storage from "@/utils/storage.js";
// 获取系统路由
import router from '@/router';

// 写入动态路由
const setDynamic = (dynamicList, callback) => {
    dynamicList.forEach((item) => {
        const viewsModules = import.meta.glob(
            "/src/**/*.vue"
        );
        const route = {
            path: item.path,
            name: item.routeName,
            redirect: "",
            children: [],
            component:
                viewsModules[
                    `/src/views/${item.modulePath}.vue`
                ],
        };
        router.addRoute('layout', route);
    });
    if(callback) {
        console.log('55555')
        callback()
    }
}

// 通过logid获取权责菜单
export const getMenuRoutes = (callback, callbackTwo) => {
    const userStoreState = userStore(pinia)
    let loginId = Storage.localGet("loginId");
    if(loginId) {
        menuHttp.menuRoutes(loginId).then((res) => {
            let roleMenuRouteList = res.data.data
            // 状态status=1启用状态list
            let hasAuthMenuRoutes = [];
            let menuRoutesIdsList = [];
            roleMenuRouteList.forEach((item) => {
                if (item.status == "1") {
                    hasAuthMenuRoutes.push(item);
                    menuRoutesIdsList.push(item.id);
                }
            });
            // 将状态status=1启用状态写入存入缓存
            Storage.localSet("hasAuthMenuRoutes", JSON.stringify(hasAuthMenuRoutes));
            userStoreState.setHasAuthMenuRoutes(hasAuthMenuRoutes)
            getMenuAuthList(menuRoutesIdsList, callbackTwo)
            setDynamic(hasAuthMenuRoutes, callback)
        })
    }
}

// 递归菜单列表，设置访问权限 hasAuth
const setRoleHasAuthMenuList = (menuList, menuRoutesIdsList) => {
    menuList.forEach((item) => {
        if (!menuRoutesIdsList.includes(item.id)) {
            item.hasAuth = false;
            if (item.children) {
                    setRoleHasAuthMenuList(item.children, menuRoutesIdsList);
                
            }
        } else {
            item.hasAuth = true;
            if (item.children) {
                setRoleHasAuthMenuList(item.children, menuRoutesIdsList);
            
            }
        }
    });
};
// 获取菜单匹配路由并存入缓存
const getMenuAuthList = (menuRoutesIdsList, callbackTwo) => {
    const userStoreState = userStore(pinia)
    let params = {
        pageNo: 1,
        pageSize: 1000,
    };
    menuHttp.menuMenuList(params).then((res) => {
        let menuList = res.data.data
        setRoleHasAuthMenuList(menuList, menuRoutesIdsList)
        Storage.localSet("menuList", JSON.stringify(menuList));
        userStoreState.setMenuList(menuList)
        console.log(menuList, 'menuRoutesIdsList')
        if(callbackTwo) {
            callbackTwo()
        }
    })
}
